package cn.bjc.filters;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.core.Ordered;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;


public class RequestTimeFilter implements GatewayFilter, Ordered {

    //构造当前类日志器,其效果和lombok提供的log4j一致
    private static final Logger log = LoggerFactory.getLogger(RequestTimeFilter.class);
    
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.打印用户请求
        String path = exchange.getRequest().getURI().getPath();
        log.info("当前请求路径为:{}",path);
        
        //2.存入进入请求时的开始时间
        exchange.getAttributes().put("startTime", System.currentTimeMillis());
        
        //3.执行完成之后
        return chain.filter(exchange).then(
                Mono.fromRunnable(() -> {
                    // 开始时间
                    Long startTime = exchange.getAttribute("startTime");
                    // 结束时间
                    Long endTime = (System.currentTimeMillis() - startTime);
                    // 打印当前请求耗时
                    log.info(exchange.getRequest().getURI().getRawPath() + ": " + endTime + "ms");
                })
        );
        
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
